import React from 'react'
// ===================================================================== global declare
const { $fn, $Lazy } = window
// ===================================================================== Lazy 
const FormItem 		= $Lazy.load(()=>import('@antd/form/layout/item'))
const Input 		= $Lazy.load(()=>import('@antd/form/input'))
const Select 		= $Lazy.load(()=>import('@antd/form/select'))
const Upload 		= $Lazy.hook(()=>import('@antd/upload'))
const DatePicker	= $Lazy.load(()=>import('@antd/form/datePicker'))
const Checkbox		= $Lazy.load(()=>import('@antd/form/checkbox'))
const CheckboxGroup = $Lazy.load(()=>import('@antd/form/checkboxGroup'))
const Radio = $Lazy.load(()=>import('@antd/form/radio'))
//
const Title 		= $Lazy.load(()=>import('#tp/title/title-small'))
// ===================================================================== private template

// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		index:0
	}
	
	// 显示与隐藏
	hide = () => this.listRef.style.display = 'none'
	show = () => this.listRef.style.display = 'block'
	
	// 按下方向键，显示列表
	onResult = (e,name) => {
		let { search } = this.props
		if(!search) return
		if(e.keyCode === 40){
			// 
			const api = [
				'knowledge-base/index', 			// 肉眼所见、病理所见、病理诊断
				'report-result-info/search',		// type = 0、结果; 1、骨髓特征、血片特征、形态学意见；2、建议与解释
			]
			const { i, p } =  search
			this.show()
			
			let { form, name } = this.props
			
			form = form.current ? form.current.refs.ref : form
			
			// 区分病理 和 其他 [2021-7-27 4:24:46 ?F10: PM?] --伍智睿
			const value = form.getName(name)
			const searchWord = i ? {result_content: value?.substring(value.length - 3)} : {keyword: value?.substring(value.length - 3), limit: 999, page: 1}			
			
			window.$http.pull(this,api[i], { param: {...p, ...searchWord } }).then(rs=>{
				window.addEventListener('keyup', this.listener)
			})
			
			if(!this.first){
				window.addEventListener('click', this.hide )
				this.first = true
			}
			this.listRef.style.top = (this.boxRef.clientHeight-18) + 'px'
			
			this.boxRef.querySelector('textarea').blur()
		}
	}
	
	// 选择
	onSelect = (e,index,{content, result_content})=>{
		e.stopPropagation()
		let { form, name } = this.props
		form = form.current.refs.ref
		let _value = form.getName(name)
		let _content = content || result_content
		form.setValue({ [name]: $fn.isValid(_value) ? _value + '\r' + _content : _content })
		this.setState({ index })
	}
	// 上下方向选择
	listener = e => {
		let { data, index } = this.state
		const len =  data.length
		e.preventDefault()
		if(e.keyCode === 40){
			this.setState(({ index })=>{
				if(index < len - 1 ){
					index ++
					return { index }
				}else {
					return { index:0 }
				}
			})
			
		}else if(e.keyCode === 38){
			this.setState(({ index })=>{
				if(index > 0 ){
					index --
					return { index }
				}else {
					return { index:len-1 }
				}
			})
		}else if(e.keyCode === 13){
			if(this.listRef.style.display !== 'none'){
				const content = data[index]?.content || data[index]?.['result_content']
				this.onSelect(e, index, { content } )
			}
		}
	}
	
	componentWillUnmount(){
		window.removeEventListener('click', this.hide )
		window.removeEventListener('keyup', this.listener)
	}
	
	render(){
		const { index, data, pullLoading } = this.state
		let { title, tit, name, controls, type, search, wrapClassName, mode, style, r, titleClassName, titleStyle,
			inputStyle, disabled, p, label, readOnly
		} = this.props
		const isSelect = type === 'select' || type === 'select'
		let _holder = tit ? tit : title
		if(label){ _holder = label }
		let txt = '请输入'
		if(isSelect){
			txt = '请选择'
		}else if(type === 'upload'){
			txt = '请上传'
		}
		
		const config = { bordered: false, size:'middel', rows: 3, outer:true }
		let children = null
		if(type === 'upload'){
			children = <Upload code={126} {...config}  {...this.props} />
		}else if(type === 'date-time'){
			children = <DatePicker {...config} {...this.props} />
		}else if(type === 'select'){
			children = <Select {...config} {...this.props} p={'选择' + _holder} />
		}else if(type === 'checkbox'){
			children = <Checkbox {...config} {...this.props} />
		}else if(type === 'checkboxGroup'){
			children = <CheckboxGroup {...config} {...this.props} />
		}else if(type === 'radio'){
			children = <Radio {...config} {...this.props} />
		}else if(type === 'html-input'){
			children = <input className='html-input' disabled={disabled} />
		}else{
			children = <Input {...config} readOnly={readOnly} p={'输入' + _holder} {...this.props} style={{inputStyle}} onClick={search?this.hide:null} onKeyUp={ search ? e=>this.onResult(e,name) : null}/>
		}
		
		return (
			<div ref={ref=>this.boxRef = ref} style={{position:'relative', ...style}} className={`
				submit-item
				${wrapClassName?wrapClassName:''}
				${mode==='textarea' ? 'el-textarea' : 'el-input'}
				${disabled ? 'form-disabled' : ''}
				${type==='upload' && !mode ? 'big-upload' : ''}
			`}>
				{ title && <Title title={title} controls={controls} className={titleClassName} style={{height:30,lineHeight:'30px',...titleStyle}} required={r} /> }
				{
					children && (
						<FormItem
							label	= { tit } 
							name	= { name } 
							noStyle	= { tit || r ? false : true }
							rules	= { [
								{ required:r, message:  p ? p : ( txt + _holder ) }
							] }
						>
							{ children }
						</FormItem>
					)
				}
				{
					search && (
						<>
							<div className='fx'>
								{ tit && <div className='ant-form-item-label'></div> }
								<p className='f12 g9' style={{marginTop:2}}>( 使用向下 " ↓ " 箭头自动搜索 )</p>
							</div>
							<dl ref={ref=>this.listRef=ref} className='abs_lt bcf f12 oys scrollbar w result-select' style={{display:'none', maxHeight:200, zIndex:100, top:132, boxShadow:'0 0 5px #ddd', border:'1px solid ' + $fn.c0}}>
								{
									$fn.hasArray(data) && data.map((v,i)=> (
										<dd key={i} style={{padding:'0 10px'}} className={`omits-1 h30 cp linear ${index === i ? 'bcm cf' : 'hover tap'}`} onClick={e=>this.onSelect(e,i,v)}>{ v.content||v.result_content }</dd>
									) )
								}
								{
									pullLoading && <dd className='f12 g9 tc ptb5'>加载中...</dd>
								}
								{
									(!pullLoading && !$fn.hasArray(data)) && <dd className='f12 g9 tc ptb5'>无快捷内容</dd>
								}
							</dl>
						</>
					)
				}
			</div>
		)
	}
	
}

export default Index